package com.shengdong.water.base

import com.shengdong.water.code.api.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import retrofit2.Response
import javax.inject.Inject

/**
 * Repository 基类
 */
open class BaseRepository @Inject constructor(

)
    {

    /**
     * 安全的网络请求
     */
    protected fun <T> safeApiCall(
        apiCall: suspend () -> Response<BaseResponse<T>>): Flow<ResultState<T>> = flow {
        try {
            val response = apiCall()
            val body = response.body()
            if (response.isSuccessful && body != null) {
                if (body.isSuccess()) {
                    body.data?.let {
                        emit(ResultState.Success(it))
                    } ?: emit(ResultState.Toast(body.msg))
                } else {
                    emit(ResultState.Error(body.code, body.msg))
                }
            } else {
                emit(ResultState.Error(-1, "未知错误"))
            }
        } catch (e: Exception) {
            emit(ResultState.Error(-1, e.message ?: "未知错误"))
        }
    }.flowOn(Dispatchers.IO)
} 

/**
 * 网络请求结果封装类
 */
sealed class ResultState<out T> {
    data class Success<out T>(val data: T) : ResultState<T>()
    data class Toast(val message: String) : ResultState<Nothing>()
    data class Error(val code: Int, val message: String) : ResultState<Nothing>()
    data class Exception(val throwable: Throwable) : ResultState<Nothing>()
    object Loading : ResultState<Nothing>()
}